package com.skytech.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.*;

/**
 * Created by Administrator on 2017/8/18.
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)})
public class LowercaseJSONInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List result = (List) invocation.proceed();
        for (Object item : result) {
            if (item instanceof JSONObject) {
                lowercaseDataItem((JSONObject) item);
            }
        }
        return result;
    }

    private void lowercaseDataItem(JSONObject row) {
        JSONObject newItem = new JSONObject();
        for (Map.Entry<String, Object> entry : row.entrySet()) {
            Object value = entry.getValue();
            newItem.put(entry.getKey().toLowerCase(), value);
            if (value.getClass().isArray()) {
                lowercaseCollection(Arrays.asList((Object[]) value));
            } else if (value instanceof Collection) {
                lowercaseCollection((Collection) value);
            } else if (value instanceof JSONObject) {
                lowercaseDataItem((JSONObject) value);
            }
        }
        row.clear();
        row.putAll(newItem);
    }

    private void lowercaseCollection(Collection collections) {
        for (Object item : collections) {
            if (item instanceof JSONObject) {
                lowercaseDataItem((JSONObject) item);
            }
        }
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
